<script setup>
import { ref, defineProps, watch, getCurrentInstance } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import {useCartStore} from "@/stores/cart.js";
import {buyMemberService, buyPackageService} from "@/api/type.js";
import {useRouter} from "vue-router";
const cart = useCartStore()
const { $t } = getCurrentInstance().proxy;
const route = useRouter()
const props = defineProps({
  type: String,
  items: String,
  total: Number
});
const paymentInfo = ref({
  cardName: '',
  cardNumber: '',
  password: '',
  paymentMethod: 'unionpay'
});
const validation = ref(true);
const validate = () => {
  validation.value = true;
  if (!paymentInfo.value.cardName || paymentInfo.value.cardName.length < 2) {
    return;
  }
  if (!paymentInfo.value.cardNumber || (paymentInfo.value.cardNumber.replace(/\s+/g, "").length !== 12 && paymentInfo.value.cardNumber.replace(/\s+/g, "").length !== 16)) {
    return;
  }
  if (!paymentInfo.value.password || paymentInfo.value.password.length < 6) {
    return;
  }
  validation.value = false;
}
watch(paymentInfo, validate, { deep: true });
const loading = ref(false);
const router = useRouter();
const Payment = async () => {
  loading.value = true;
  try {
    let res;
    if(props.type === 'cart'){
      res = await buyPackageService(cart.cartItems)
    }else{
      res = await buyMemberService(props.items)
    }
    if (res.code === 0) {
      let seconds = 3;
      const msg = ref($t('paymentSuccessMessage'));
      cart.clearCart();
      ElMessageBox({
        title: $t('paymentSuccessTitle'),
        type: 'success',
        message: msg.value,
        showConfirmButton: false,
        showClose: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        lockScroll: true,
        distinguishCancelAndClose: true
      });
      const timer = setInterval(() => {
        seconds--;
        if (seconds <= 0) {
          clearInterval(timer);
          ElMessageBox.close();
          router.replace('/main');
        }
      }, 1000);
    } else {
      ElMessage.error(res.message || $t('paymentFailed'));
    }
  } catch (e) {
    ElMessage.error($t('networkError'));
  } finally {
    loading.value = false;
  }
};

const formatCardNumber = (value) => {
  return value
    .replace(/\D/g, '')
    .replace(/(\d{4})(?=\d)/g, '$1 ')
    .trim();
};

const handleCardNumberInput = (event) => {
  const rawValue = event.target.value;
  const formattedValue = formatCardNumber(rawValue);
  paymentInfo.value.cardNumber = formattedValue;
};
</script>

<template>
  <div class="checkout-container">
    <h2 class="section-title"><i class="fas fa-credit-card"></i> {{ $t("paymentInfo") }} </h2>

    <div class="form-group">
      <label for="cardName"> {{ $t("cardHolder") }} </label>
      <input type="text" id="cardName" class="form-control" :placeholder="$t('cardHolderPlaceholder')" v-model="paymentInfo.cardName" />
    </div>

    <div class="form-group">
      <label for="cardNumber"> {{ $t("cardNumber") }} </label>
      <input type="text" id="cardNumber" class="form-control"
        :placeholder="paymentInfo.paymentMethod === 'unionpay' ? '**** **** **** ****' : '**** **** ****'"
        v-model="paymentInfo.cardNumber" maxlength="19" @input="handleCardNumberInput" />
    </div>

    <div class="form-group">
      <label for="pwd"> {{ $t("paymentPassword") }} </label>
      <input type="text" id="pwd" class="form-control" placeholder="PWD" v-model="paymentInfo.password" />
    </div>

    <div class="payment-methods">
      <div class="payment-method" :class="{ selected: paymentInfo.paymentMethod === 'unionpay' }"
        @click="paymentInfo.paymentMethod = 'unionpay'">
        <img src="@/assets/icons/Unionpay.svg" alt="UnionPay" />
        <div>{{ $t("unionpay") }}</div>
      </div>
      <div class="payment-method" :class="{ selected: paymentInfo.paymentMethod === 'visa' }"
        @click="paymentInfo.paymentMethod = 'visa'">
        <i class="fab fa-cc-visa"></i>
        <div>Visa</div>
      </div>
      <div class="payment-method" :class="{ selected: paymentInfo.paymentMethod === 'mastercard' }"
        @click="paymentInfo.paymentMethod = 'mastercard'">
        <i class="fab fa-cc-mastercard"></i>
        <div>{{ $t("mastercard") }}</div>
      </div>
    </div>

    <el-button class="pay-btn" type="primary" :loading="loading" :disabled="validation" @hover="validate"
      @click="Payment">
      <i class="fas fa-lock"></i> {{ $t("payButton") }} ¥ {{ props.total.toFixed(2) }}
    </el-button>

    <div class="secure-note">
      <i class="fas fa-shield-alt"></i> {{ $t("secureNote") }}
    </div>
  </div>
</template>

<style scoped>
.checkout-container {
  background: var(--card-bg);
  border-radius: 15px;
  animation: fadeIn 0.8s ease-out;
  padding: 20px;
}

.section-title {
  font-size: 1.5rem;
  margin-bottom: 20px;
  color: var(--cart-text);
  display: flex;
  align-items: center;
  gap: 10px;
}

.section-title i {
  color: #3498db;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: var(--h4-color);
}

.form-control {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 1rem;
  transition: border-color 0.3s;
  background-color: var(--select-color);
  color: var(--h4-color);
}

.form-control::placeholder {
  color: var(--arrow2-color);
}

.form-control:focus {
  border-color: #3498db;
  outline: none;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
}

.payment-methods {
  display: flex;
  gap: 15px;
  margin: 15px 0;
}

.payment-method {
  flex: 1;
  border: 2px solid #eee;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  color: var(--h4-color);
}

.payment-method:hover,
.payment-method.selected {
  border-color: #3498db;
  background: rgba(52, 152, 219, 0.05);
}

.payment-method i {
  font-size: 2rem;
  margin-bottom: 10px;
  color: #3498db;
}

.payment-method img {
  width: 2.4rem;
  height: 2.4rem;
  font-size: 2rem;
  display: block;
  margin: 0 auto 5px auto;
  object-fit: contain;
}

.pay-btn {
  background: linear-gradient(90deg, #3498db, #8e44ad);
  color: white;
  border: none;
  width: 100%;
  height: 3vw;
  padding: 15px;
  border-radius: 8px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 10px;
  box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
}

.pay-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
}

.secure-note {
  text-align: center;
  color: #27ae60;
  margin-top: 15px;
  font-size: 0.9rem;
}

.secure-note i {
  margin-right: 5px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>